<template>
  <a-form
    :form="form"
    :label-col="{ span: 8 }"
    :wrapper-col="{ span: 12 }"
    @submit="handleSubmit"
  >
    <a-form-item label="服务器（V）">
      <a-input
        v-decorator="[
          'server',
          {
            rules: [{ required: true, message: '请填写服务器!' }],
            initialValue: dataConfig.server,
          },
        ]"
        class="col-container"
        size="small"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item label="端口（R）">
      <a-input
        v-decorator="[
          'port',
          {
            rules: [{ required: true, message: '请填写端口!' }],
            initialValue: dataConfig.port,
          },
        ]"
        class="col-container"
        size="small"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item
      v-if="selectedDatabaseType === databaseMapping.oracle"
      label="服务名或SID"
    >
      <a-input
        v-decorator="[
          'connectValue',
          {
            rules: [{ required: true, message: '请填写服务名或SID!' }],
            initialValue: dataConfig.connectValue,
          },
        ]"
        class="col-container"
        size="small"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
      <a-radio-group
        v-decorator="[
          'connectType',
          {
            rules: [{ required: true, message: '服务名或SID!' }],
            initialValue: 'servicename',
          },
        ]"
        @change="changeDatabaseConfig"
      >
        <a-radio class="radio-container" value="servicename">服务名</a-radio>
        <a-radio class="radio-container" value="sid">SID </a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="输入数据库登录信息" style="margin-top: 12px;" />
    <a-form-item label="用户名（U）">
      <a-input
        v-decorator="[
          'user',
          {
            rules: [{ required: true, message: '请填写用户名!' }],
            initialValue: dataConfig.user,
          },
        ]"
        class="col-container"
        size="small"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item label="密码（P）">
      <a-input
        v-decorator="[
          'password',
          {
            rules: [{ required: true, message: '请填写密码!' }],
            initialValue: dataConfig.password,
          },
        ]"
        class="col-container"
        size="small"
        type="password"
        placeholder="请填写"
        @change="changeDatabaseConfig"
      >
      </a-input>
    </a-form-item>
    <a-form-item label="链接测试">
      <div class="col-container testing">
        <a-button
          v-if="testState === 'BEFORE_TEST'"
          type="link"
          style="padding: 0;"
          html-type="submit"
        >
          点击测试
        </a-button>
        <a-spin v-else-if="testState === 'TESTING'" />
        <span v-else-if="testState === 'TEST_SUCCEED'" style="color: #78c06e;">
          连接成功
          <a-icon type="check-circle" style="color: #78c06e;" theme="filled" />
        </span>
        <span v-else>
          链接失败
          <a-icon type="close-circle" theme="filled" />
          <a-button type="link" html-type="submit">重新测试</a-button>
        </span>
      </div>
    </a-form-item>
    <!-- <a-form-item v-if="testState==='TEST_SUCCEED'" label="数据库（D）">
        <a-select
          v-decorator="[
            'databaseName',
            { rules: [{ required: true, message: '请选择数据库!' }] },
          ]"
          placeholder="请选择"
          class="col-container"
          size="small"
          @change="changeSelectedDatabase"
        >
          <a-select-option v-for="option in databaseOptions" :key="option" :value="option">
            {{option}}
          </a-select-option>
        </a-select>
      </a-form-item> -->
  </a-form>
  <!-- </a-modal> -->
</template>

<script lang="ts">
/**
 * modal of testing database
 * @author Huihua Lu
 */
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import DataStore, { DatabaseTestState } from '@/store/modules/data'

const defaultConfig = {
  databaseName: '',
  databaseType: '',
  password: '',
  port: '',
  server: '',
  tableName: '',
  user: '',
}

@Component
export default class DatabaseModal extends Vue {
  @Prop() selectedDatabaseType!: string

  private form: any

  private selectedDatabase: string = ''

  private isDatabaseSelected: boolean = false

  private databaseMapping = {
    mysql: 'MySql',
    oracle: 'oracle',
  }

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'database_form' })
  }

  public get testState() {
    return DataStore.testState
  }

  public get databaseOptions() {
    return DataStore.databaseOptions
  }

  public get selectedDatasetInfo() {
    return DataStore.selectedDatasetInfo
  }

  public get dataConfig() {
    if (this.selectedDatasetInfo && this.selectedDatasetInfo.dataConfig) {
      return this.selectedDatasetInfo.dataConfig
    }
    return defaultConfig
  }

  public handleSubmit(event: Event) {
    event.preventDefault()
    this.form.validateFields(async (error: Error, values: any) => {
      if (!error) {
        const { connectType, connectValue } = values
        let passData: any = {
          databaseType: this.selectedDatabaseType,
          server: values.server,
          port: values.port,
          user: values.user,
          password: values.password,
        }
        if (this.selectedDatabaseType === this.databaseMapping.oracle) {
          passData = {
            ...passData,
            connectType,
            connectValue,
          }
        }
        DataStore.setDatabaseConfig(passData)
        await DataStore.testConnection(passData)
      } else {
        console.log('error:', error)
      }
    })
  }

  // 编辑数据库连接信息
  public changeDatabaseConfig() {
    DataStore.setTestState(DatabaseTestState.BEFORE_TEST)
    this.$emit('set-is-database-chosen', false)
  }

  public changeSelectedDatabase(value: string) {
    this.selectedDatabase = value
    this.isDatabaseSelected = true
    // this.importDatabase()
  }

  @Watch('isDatabaseSelected')
  importDatabase() {
    if (this.isDatabaseSelected) {
      // event.preventDefault()
      if (this.testState !== DatabaseTestState.TEST_SUCCEED) {
        // 还未通过测试时，点击确定会提示进行测试
        this.$message.error('请先进行数据库链接测试!')
        return
      }
      this.form.validateFields(async (error: Error, values: any) => {
        // 通过测试后，点击确定会提交相应数据，并获取所有表
        if (!error) {
          const passData = {
            ...DataStore.databaseConfig,
            databaseName: values.databaseName,
          }
          DataStore.setDatabaseConfig(passData)
          console.log(
            '-----------,database--------',
            values.databaseName,
            '-------',
            passData
          )
          await DataStore.queryDatabaseTables(passData)
          this.$emit('set-is-database-chosen', true)
          DataStore.setSelectedTables([])
          this.isDatabaseSelected = false
        } else {
          console.log('error:', error)
        }
      })
    }
    console.log(this.form)
  }

  public get isClear() {
    return DataStore.isClearForm
  }
  @Watch('isClear')
  clearForm() {
    if (this.isClear) {
      this.form.resetFields()
      // DataStore.setIsClearForm(false)
    }
  }
}
</script>
<style lang="less" scoped>
/* 表格行的样式 */
.ant-row {
  margin: 0;
}

.col-container {
  border-radius: 4px;
  margin-left: 8px;

  &.testing {
    padding-top: 2px;
  }
}
</style>
